/**
 * @字典查找
 *
 * @author	 wangshikun <wangshikun2010@gmail.com>
 * @copyright	(c) 2012 wangshikun <wangshikun2010@gmail.com>
 * @license	http://www.opensource.org/licenses/mit-license.php The MIT License
 * @package	default
 * @subpackage	default
 */

#include <stdio.h>
#include <cs50.h>

struct entry {
	char word[15];
	char definition[50];
};

int lookup(const struct entry dictionary[], const char search[], const int entries);
bool g(const char s1[], const char s2[]);

int main(void) {

	//声明一个字典
	const struct entry dictionary[100] = {
		{"a", "英文第一个字母"},
		{"b", "英文第二个字母"},
		{"c", "英文第三个字母"},
		{"d", "英文第四个字母"},
		{"e", "英文第五个字母"},
		{"f", "英文第六个字母"},
		{"g", "英文第七个字母"},
		{"h", "英文第八个字母"},
		{"i", "英文第九个字母"},
		{"j", "英文第十个字母"}
	};

	char words[10];
	int entries = 10;
	int entry;

	//将输入的单词保存在words数组里面
	printf("输入一个单词: ");
	scanf("%s", words);

	//调用lookup函数
	entry = lookup(dictionary, words, entries);

	//如果找到了，就打印出来
	if (entry != -1) {
		printf("%s\n", dictionary[entry].definition);
	} else {
		printf("对不起，没有找到%s单词\n", words);
	}
}

//查找
int lookup(const struct entry dictionary[], const char search[], const int entries) {
	int i;

	//遍历所有的字母，如果要搜索的字典里面有，就返回一个数
	for (i=0; i<entries; i++) {
		if (g(search, dictionary[i].word)) {
			return i;
		}
	}

	return -1;
}
 
//比较两个字符串是否相等
bool g(const char s1[], const char s2[]) {
	int i = 0;
	bool s;

	//两个字符串的值一样，并且都没有结束，就一直比下去
	while(s1[i] == s2[i] && s1[i] != '\0' && s2[i] != '\0')  {
		i++;
	}

	//如果两个同时到达结尾，说明两个字符串相等
	if (s1[i] == '\0' && s2[i] == '\0') {
		s = true;
	} else {
		s = false;
	}

	return s;
}
